/*
 * @Date: 2025-06-10 16:13:08
 * @Auth: 463997479@qq.com
 * @LastEditors: 463997479@qq.com
 * @LastEditTime: 2025-09-04 10:14:57
 * @FilePath: \corpus\src\pages\User\Login\index.tsx
 */
import { login } from '@/services/ant-design-pro/api';

import { history, useModel } from '@umijs/max';

import { message, Result } from 'antd';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import YkzQrcode from '../YkzQrcode';

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [errorMsg, setErrorMsg] = useState('');

  function getUrlParams(key: string) {
    let reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
    let r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  }

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (data: { code: string; loginMode: string }) => {
    try {
      const res: any = await login({ ...data });
      if (res.success === true) {
        message.success('登录成功！');
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      }
    } catch (error) {
      setErrorMsg('登录失败，请重试！');
      message.error('登录失败，请重试！');
    }
  };
  useEffect(() => {
    if (getUrlParams('auth_code')) {
      handleSubmit({ code: getUrlParams('auth_code') as string, loginMode: '1' });
    } else if (getUrlParams('token')) {
      handleSubmit({ code: getUrlParams('token') as string, loginMode: '3' });
    }
  }, []);
  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {getUrlParams('auth_code') ? (
        <Result
          style={{ flex: 1 }}
          status="error"
          title="登录状态失效，请在渝快政中打开应用！"
          subTitle={errorMsg}
        />
      ) : (
        <YkzQrcode />
      )}
    </div>
  );
};

export default Login;
